package com.redispro.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.*;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 李 力
 * @Date: 2024/11/26
 * @Description: com.redispro.utils
 * @version: 1.0
 */
public class SimpleRedisLock implements ILock {

    //不同的业务有不同的锁
    private String name;

    private static final String KEY_PREFIX = "lock:";

    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    private StringRedisTemplate template;

    private static final DefaultRedisScript<Long> unlockScript;

    static {
        unlockScript = new DefaultRedisScript<>();
        unlockScript.setLocation(new ClassPathResource("unlock.lua"));
        unlockScript.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate template) {
        this.name = name;
        this.template = template;
    }

    //尝试获取锁: value值尽量带上线程标识
    @Override
    public boolean tryLock(long timeout) {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        return Boolean.TRUE.equals(template.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeout, TimeUnit.SECONDS));
    }

    //释放锁
//    @Override
//    public void unlock() {
//        //获取线程标识
//        String threadId = template.opsForValue().get(KEY_PREFIX + name);
//        if (StrUtil.isBlank(threadId)) {
//            return;
//        }
//        //比对
//        String reallyThreadId = ID_PREFIX + Thread.currentThread().getId();
//        if (threadId.equals(reallyThreadId)) {
//            template.delete(KEY_PREFIX + name);
//        }
//    }

    @Override
    public void unlock() {
        template.execute(unlockScript,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }

}
